import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router'
import { ElMessage } from 'element-plus'
import NProgress from 'nprogress' // 进度条
import 'nprogress/nprogress.css' // 进度条样式

// 进度条配置
NProgress.configure({ 
  easing: 'ease',
  speed: 500,
  showSpinner: false,
  trickleSpeed: 200,
  minimum: 0.3
})

// 路由懒加载配置
const lazyLoad = (component: string) => {
  return () => import(/* webpackChunkName: "[request]" */ `../views/${component}.vue`)
}

// 路由配置
const routes: Array<RouteRecordRaw> = [
  {
    path: '/',
    redirect: '/login',
    meta: { title: '重定向到登录页' }
  },
  {
    path: '/login',
    name: 'Login',
    component: lazyLoad('Login'),
    meta: { 
      title: '登录 - 高校教师学术成果信息综合管理系统',
      keepAlive: false
    }
  },
  {
    path: '/auth-test',
    name: 'AuthTest',
    component: lazyLoad('AuthTest'),
    meta: { 
      title: '认证测试页面',
      keepAlive: false
    }
  },
  {
    path: '/admin',
    name: 'AdminLayout',
    component: lazyLoad('admin/Layout'),
    meta: { 
      requiresAuth: true, 
      role: 'ADMIN',
      title: '管理员工作台'
    },
    redirect: { name: 'AdminDashboard' },
    children: [
      {
        path: 'dashboard',
        name: 'AdminDashboard',
        component: lazyLoad('admin/Dashboard'),
        meta: { 
          title: '管理控制台 - 高校教师学术成果信息综合管理系统',
          icon: 'Monitor',
          keepAlive: true
        }
      },
      {
        path: 'users',
        name: 'UserManagement',
        component: lazyLoad('admin/Users'),
        meta: { 
          title: '教师用户授权管理 - 高校教师学术成果信息综合管理系统',
          icon: 'User',
          keepAlive: false
        }
      },
      {
        path: 'profile',
        name: 'AdminProfile',
        component: lazyLoad('Profile'),
        meta: { 
          title: '个人信息 - 高校教师学术成果信息综合管理系统',
          icon: 'UserFilled',
          keepAlive: false
        }
      }
    ]
  },
  {
    path: '/teacher',
    name: 'TeacherLayout',
    component: lazyLoad('teacher/Layout'),
    meta: { 
      requiresAuth: true, 
      role: 'TEACHER',
      title: '教师工作台'
    },
    redirect: { name: 'TeacherDashboard' },
    children: [
      {
        path: 'dashboard',
        name: 'TeacherDashboard',
        component: lazyLoad('teacher/Dashboard'),
        meta: { 
          title: '教师控制台 - 高校教师学术成果信息综合管理系统',
          icon: 'Monitor',
          keepAlive: true
        }
      },
      {
        path: 'students',
        name: 'StudentManagement',
        component: lazyLoad('teacher/StudentManagement'),
        meta: { 
          title: '研究生管理 - 高校教师学术成果信息综合管理系统',
          icon: 'User',
          keepAlive: false
        }
      },
      {
        path: 'achievements',
        name: 'TeacherAchievements',
        component: lazyLoad('teacher/Achievements'),
        meta: { 
          title: '教师成果管理 - 高校教师学术成果信息综合管理系统',
          icon: 'Trophy',
          keepAlive: false
        }
      },
      {
        path: 'approvals',
        name: 'ApprovalManagement',
        component: lazyLoad('teacher/ApprovalManagement'),
        meta: { 
          title: '成果评审管理 - 高校教师学术成果信息综合管理系统',
          icon: 'DocumentChecked',
          keepAlive: false
        }
      },
      {
        path: 'profile',
        name: 'TeacherProfile',
        component: lazyLoad('Profile'),
        meta: { 
          title: '个人信息 - 高校教师学术成果信息综合管理系统',
          icon: 'UserFilled',
          keepAlive: false
        }
      }
    ]
  },
  {
    path: '/student',
    name: 'StudentLayout',
    component: lazyLoad('student/Layout'),
    meta: { 
      requiresAuth: true, 
      role: 'STUDENT',
      title: '学生工作台'
    },
    redirect: { name: 'StudentDashboard' },
    children: [
      {
        path: 'dashboard',
        name: 'StudentDashboard',
        component: lazyLoad('student/Dashboard'),
        meta: { 
          title: '学生控制台 - 高校教师学术成果信息综合管理系统',
          icon: 'Monitor',
          keepAlive: true
        }
      },
      {
        path: 'achievements',
        name: 'StudentAchievements',
        component: lazyLoad('student/Achievements'),
        meta: { 
          title: '个人学术成果 - 高校教师学术成果信息综合管理系统',
          icon: 'Trophy',
          keepAlive: false
        }
      },
      {
        path: 'profile',
        name: 'StudentProfile',
        component: lazyLoad('Profile'),
        meta: { 
          title: '个人信息 - 高校教师学术成果信息综合管理系统',
          icon: 'UserFilled',
          keepAlive: false
        }
      }
    ]
  },
  {
    path: '/:pathMatch(.*)*',
    name: 'NotFound',
    component: lazyLoad('NotFound'),
    meta: { 
      title: '页面未找到 - 高校教师学术成果信息综合管理系统'
    }
  }
]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes,
  scrollBehavior(to, from, savedPosition) {
    if (savedPosition) {
      return savedPosition
    } else {
      return { top: 0 }
    }
  }
})

// 全局前置守卫
router.beforeEach((to, from, next) => {
  // 开始进度条
  NProgress.start()
  
  // 设置页面标题
  if (to.meta.title) {
    document.title = to.meta.title as string
  }
  
  const userRole = localStorage.getItem('userRole')
  const user = localStorage.getItem('user')

  // 访问权限控制
  if (to.matched.some(record => record.meta.requiresAuth)) {
    // 未登录，重定向到登录页
    if (!user) {
      ElMessage.warning('请先登录')
      next({ 
        name: 'Login', 
        query: { redirect: to.fullPath } // 记录重定向来源
      })
    } 
    // 检查角色权限
    else if (to.meta.role && to.meta.role !== userRole) {
      ElMessage.error('无权限访问该页面')
      next({ name: 'NotFound' })
    } 
    else {
      next()
    }
  } 
  // 已登录用户访问登录页，重定向到对应的首页
  else if (to.name === 'Login' && user) {
    if (userRole === 'ADMIN') {
      next({ name: 'AdminDashboard' })
    } else if (userRole === 'TEACHER') {
      next({ name: 'TeacherDashboard' })
    } else if (userRole === 'STUDENT') {
      next({ name: 'StudentDashboard' })
    } else {
      next()
    }
  } 
  else {
    next()
  }
})

// 全局后置钩子
router.afterEach(() => {
  // 结束进度条
  NProgress.done()
})

export default router 